package com.knife.common.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * IP相关工具类
 *
 * @author 陌溪
 * @date 2020年1月21日10:36:35
 */
public class KnifeIpUtil {

    public static final String X_FORWARDED_FOR = "x-forwarded-for";
    public static final String UNKNOWN = "unknown";
    public static final String AN_OBJECT = "0:0:0:0:0:0:0:1";
    public static final String AN_OBJECT1 = "127.0.0.1";
    public static final String PROXY_CLIENT_IP = "Proxy-Client-IP";
    public static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    /**
     * 获取当前网络ip
     *
     * @param request 当前请求信息
     * @return ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader(X_FORWARDED_FOR);
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(PROXY_CLIENT_IP);
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(WL_PROXY_CLIENT_IP);
        }
        if (ipAddress == null || ipAddress.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals(AN_OBJECT1) || ipAddress.equals(AN_OBJECT)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  //"***.***.***.***".length() = 15
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获取真实IP
     *
     * @param request 请求信息
     * @return ip地址
     */
    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader(X_FORWARDED_FOR);
        return checkIp(ip) ? ip : (
                checkIp(ip = request.getHeader(PROXY_CLIENT_IP)) ? ip : (
                        checkIp(ip = request.getHeader(WL_PROXY_CLIENT_IP)) ? ip :
                                request.getRemoteAddr()));
    }

    /**
     * 校验IP
     *
     * @param ip ip
     * @return 是否有效IP
     */
    private static boolean checkIp(String ip) {
        return !StringUtils.isEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip);
    }
}
